using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Logic;
using System.Collections.Generic;

namespace IQIGame.Onigao.GamePlay
{
    /// <summary>
    /// 服务
    /// 注意每一个服务对应唯一一个触发器，不同服务的触发器类型和参数不可能完全相同
    /// 每一个服务下有多个服务单元，条件是在服务单元里判断的
    /// 服务只负责组合唯一的一种触发器（由类型和参数共同定义）和所有的服务单元。
    /// </summary>
    public class ServiceNonLevel : IReusableClass
    {
        private TViewEntity _host;
        private List<ServiceUnitNonLevel> _units = new();

        public uint MaxStore => 100;
        public BaseNonLevelServiceTrigger trigger { get; private set; }
        /// <summary>
        /// 服务在实体身上的索引
        /// </summary>
        public int index { get; private set; }

        public static ServiceNonLevel Create(TViewEntity host, MainCityServiceConfig config, int index)
        {
            var service = ClassPool<ServiceNonLevel>.Get();
            service.Init(host, config, index);
            return service;
        }

        private void Init(TViewEntity host, MainCityServiceConfig config, int index)
        {
            this._host = host;
            this.trigger = MainCityServiceFactory.CreateTrigger(config);
            this.trigger.InitHost(host);
            foreach (var unitCid in config.serviceUnits)
            {
                var unit = ClassPool<ServiceUnitNonLevel>.Get();
                unit.Init(_host, unitCid);
                _units.Add(unit);
            }
            this.index = index;
        }

        public bool Trigger(object dynamicObjParam, TrigValueTypeParam dynamicValueTypePram)
        {
            return trigger.OnTrigger(dynamicObjParam, dynamicValueTypePram);
        }

        public int Execute()
        {
            int num = 0;
            foreach (var unit in _units)
            {
                num += unit.Execute();
            }
            return num;
        }

        public void Put2Pool()
        {
            ClassPool<ServiceNonLevel>.Put(this);
        }

        public void OnReset()
        {
            index = 0;
            _host = null;
            ClassPool.PutAutoType(trigger);
            trigger = null;
            foreach (var unit in _units)
            {
                ClassPool<ServiceUnitNonLevel>.Put(unit);
            }
            _units.Clear();
        }
    }
}
